/**
 * 病种入组病例管理初始化
 */
var SdsMedicalGroup = {
    id: "SdsMedicalGroupTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    hospID: null,
    episodeId: 0,
    clicked: false,
    checkPerm: $("#checkPerm").val(), // 审核权限
    submitPerm: $("#submitPerm").val(), // 填报权限
    docUpPerm: $("#formCheckType").val(), // 医生能否直接上报配置
    enableIPQC: $("#enableIPQC").val() // 是否启用过程质控
};

/**
 * 初始化表格的列
 */
SdsMedicalGroup.initColumn = function () {
    var columnArr = [
        {
            width: 30, align: "center", valign: 'middle', sortable: true, formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize = $('#SdsMedicalGroupTable').bootstrapTable('getOptions').pageSize;
                //获取当前是第几页
                var pageNumber = $('#SdsMedicalGroupTable').bootstrapTable('getOptions').pageNumber;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        },
        {title: '科室', field: 'admLocDesc', width: 120, align: 'left', valign: 'middle'},
        {
            title: '病案号',
            field: 'mrNum',
            width: 100,
            align: 'left',
            valign: 'middle',
            formatter: function (value, row, index) {
                // 设置该列鼠标悬浮显示系统内就诊号，方便查找调试
                var span = document.createElement('span');
                span.setAttribute('title', row.id);
                span.innerHTML = value;
                return span.outerHTML;
            }
        },
        // {title: '就诊号', field: 'id', width:100, align: 'left', valign: 'middle'},
        {title: '姓名', field: 'name', width: 100, align: 'left', valign: 'middle'},
        {title: '性别', field: 'sex', width: 30, align: 'center', valign: 'middle'},
        {title: '年龄', field: 'age', width: 30, align: 'center', valign: 'middle'},
        {title: '主管医生', field: 'admDocName', width: 80, align: 'left', valign: 'middle'},
        {title: '入院日期', field: 'admDate', width: 120, align: 'left', valign: 'middle'},
        {title: '出院日期', field: 'dishDate', width: 120, align: 'left', valign: 'middle'},
        {title: '在院质控病种', field: 'admEntityName', width: 140, align: 'left', valign: 'middle'},
        {
            title: '病种名称',
            field: 'entityName',
            width: 140,
            align: 'left',
            valign: 'middle',
            formatter: function (value, row, index) {
                if (row.state != 'O') {
                    return value;
                }
                if (row.isAuto != 0) {
                    value += '(系统排除)'
                } else {
                    value += '(手动排除)'
                }
                return '<span style="color: #cc0000">'+value+'</span>'
            }
        },
        {
            title: '操作',
            field: 'id',
            align: 'center',
            width: '80px',
            valign: 'middle',
            formatter: function (value, row, index) {
                var _html = '';
                if (row.qcincaseId == "" || row.state == "O" || row.state == 'P') {
                    //未入组 和 已排除
                    _html = '<a href="javascript:SdsMedicalGroup.inGroup(\'' + row.id + '\')" title="入组"><i class="hisui-icon icon-add-item"></i></a>';
                } else {
                    //已入组
                    _html = '<a href="javascript:SdsMedicalGroup.edit(\'' + row.id + '\',\'' + row.qcincaseId + '\',\'' + row.name + '\',\'' + row.mrNum + '\',\'' + row.dishDate + '\')" title="填报"><i class="hisui-icon icon-write-order"></i></a>';
                    if (row.state != "Up") {
                        _html += '<a href="javascript:SdsMedicalGroup.del(\'' + row.qcincaseId + '\',\'' + row.entityId + '\')" title="排除"><i class="hisui-icon icon-cancel"></i></a>';
                        // _html += '<a href="javascript:SdsMedicalGroup.up(\''+row.qcincaseId+'\',\''+row.name+'\')" title="上报"><i class="hisui-icon icon-upload-cloud"></i></a>';
                    }
                }
                return _html;
            }
        }];

    // 如果未启用过程质控模块，则不增加在院质控病种一列
    if ($('#enableIPQC').val() != "Y") {
        columnArr.splice(9, 1);
    }

    return columnArr;
};

/**
 * 检查是否选中
 */
SdsMedicalGroup.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Sys.info("请先选中表格中的某一记录！");
        return false;
    } else {
        SdsMedicalGroup.seItem = selected[0];
        return true;
    }
};

/**
 * 点击新增病种入组病例
 */
SdsMedicalGroup.add = function () {
    var index = Sys.open('新增病种入组病例', Sys.backendPath + '/sds/sdsqcincase/to_add', ['800px', '420px']);
    this.layerIndex = index;
};

/**
 * 打开查看病种入组病例详情
 */
SdsMedicalGroup.edit = function (episodeId, id, name, mrNum, dishDate) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        // 未启用过程质控模块直接打开填报表单
        if (SdsMedicalGroup.enableIPQC == 'Y') {
            SdsMedicalGroup.GetMrListIfo(episodeId, id, name, mrNum, dishDate);
        } else {
            SdsMedicalGroup.openFormWin(id, name, mrNum, dishDate);
        }
    }
};

SdsMedicalGroup.GetMrListIfo = function (episodeId, mrListId, name, mrNum, dishDate) {
    var mrlistInfo;
    var ajax = new $ax("/sds/sdsqcincase/getMrListInfo", function (data) {
        mrlistInfo = data;
    }, function () {
    });
    ajax.setData({"episodeId": episodeId});
    ajax.start();
    if (!$.isEmptyObject(mrlistInfo)) {
        var mrListId = mrlistInfo.mrlistIdOut;
        var entityIdOut = mrlistInfo.entityIdOut;
        var entityNameOut = mrlistInfo.entityNameOut;
        var entityIdIn = mrlistInfo.entityIdIn;
        var entityNameIn = mrlistInfo.entityNameIn;
        var tipsStr = "\t<p style='color:#ff7e00;background-color:#fff3dd;border: 1px solid #f7d199;text-indent:2em;'>该患者在院质控病种和出院入组筛查病种不一致，请选择并确认上报病种！</p>\n";
        tipsStr += "\t<div style='display: block;padding: 5px;'>\n"
        tipsStr += "\t<label>出院筛查病种：</label><input type=\"radio\" name=\"entityId\" value=\"" + entityIdOut + "\" checked>\n" + "<span style='color: #29723C'>" + entityNameOut + "</span>";
        tipsStr += "\t<br>\n";
        tipsStr += "\t<label>在院质控病种：</label><input type=\"radio\" name=\"entityId\" value=\"" + entityIdIn + "\">\n" + "<span style='color: #29723C'>" + entityNameIn + "</span>";
        tipsStr += "\t</div>\n";
        $("#mrListInfoHtml").html(tipsStr);
        var titleIndex = layer.open({
            type: 1,
            title: ['单病种填报提醒', 'padding-left:10px;background:#556983;color:white;'],
            content: $("#mrListInfoDiv"),
            area: ['350px', '250px'], //宽高
            fix: false, //不固定
            maxmin: false,
            skin: 'layer-ext-hisui',
            zIndex: 1100,
            btn: ['确定'],
            btnAlign: 'c',
            yes: function (index, layero) {
                layer.close(titleIndex);
                $.messager.progress({title: "提示", msg: '变更病种并自动采集填报数据', text: '采集中....'});
                SdsMedicalGroup.changeMrEntity(mrListId, $('input[name="entityId"]:checked').val());
                $.messager.progress('close');
                SdsMedicalGroup.openFormWin(mrListId, name, mrNum, dishDate);
            }
        });
    } else {
        SdsMedicalGroup.openFormWin(mrListId, name, mrNum, dishDate)
    }
};

SdsMedicalGroup.changeMrEntity = function (mrListId, entityId) {
    var ajax = new $ax("/sds/sdsqcincase/changeMrEntity", function (data) {
    }, function (data) {
    });
    ajax.setData({"mrListId": mrListId, "entityId": entityId});
    ajax.start();
};

// 打开表单填报窗口
SdsMedicalGroup.openFormWin = function (mrListId, name, mrNum, dishDate) {
    var title = "姓名:" + name + "|" + "病案号:" + mrNum + "|" + "出院日期:" + dishDate;
    var index = Sys.open_c(title, '/sds/sdsqcformshow?mrListId=' + mrListId + '&checkPerm=' + SdsMedicalGroup.checkPerm + '&submitPerm=' + SdsMedicalGroup.submitPerm, null, function () {
        SdsMedicalGroup.table.refresh();
    });
    this.layerIndex = index;
}

/**
 * 删除病种入组病例
 */
SdsMedicalGroup.del = function (id, entityId) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        entityId = this.seItem.entityId;
        flag = true;
    }
    if (flag) {
        //打开 弹出框
        var index = layer.open({
            type: 2,
            title: ['排除单病种【信息录入】'],
            area: ['600px', '400px'],
            zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
            content: "/sds/sdsqcformshow/excludereason?mrListId=" + id + "&entityId=" + entityId,
            skin: 'layer-ext-hisui',
            scrollbar: false//为了禁止父页面滚动条滚动
        });
        this.layerIndex = index;

        //监听子页面的postMessage
        function receiveMessage(event) {
            //取得子页面传回来的值
            if (event.data == "close") {
                // 如果传回close，关闭当前弹窗
                layer.close(index);
            }
            if (event.data == "save") {
                SdsMedicalGroup.table.refresh();
                setTimeout(function () {
                    layer.close(index);
                }, 1000);
            }
        }

        window.addEventListener('message', receiveMessage, false);
    }
};

/**
 * 点击上报病种
 */
SdsMedicalGroup.up = function (id, name) {
    console.log("上报病种...")
};


function Common_CheckboxToSDRule() {
    var ItemCode = arguments[0];
    var ParRef = arguments[1];
    var RuleType = arguments[2];
    var columns = arguments[3] ? arguments[3] : 4;
    var params = {};
    var ajax = new $ax(Sys.backendPath + "/sds/sdsopqcincase/selectRulesByQcEntityId", function (data) {
        //加载表格数据
        var dicList = data.split(";");
        if (dicList[0] == "") {
            $('#' + ItemCode).html("");
            return;
        }
        var len = dicList.length;
        var count = parseInt(len / columns) + 1;
        var per = Math.round((1 / columns) * 100) + '%';  //每列所在百分比，等比分布

        var listHtml = ""
        for (var index = 0; index < count; index++) {
            var chklen = (((index + 1) * columns) < len) ? (index + 1) * columns : len;
            listHtml += "<div style='width: 90%;'>";
            for (var dicIndex = index * columns; dicIndex < chklen; dicIndex++) {
                var dicSubList = dicList[dicIndex].split(",");

                listHtml += "<input id=" + ItemCode + dicSubList[0] + " type='checkbox' class='hisui-checkbox' " + (dicSubList[0] == 1 ? "checked='true'" : "") + " label= '" + dicSubList[1] + "'  name=" + ItemCode + "  value=" + dicSubList[0] + ">";
            }
            listHtml += "</div>"
        }
        $('#' + ItemCode).html(listHtml);
        $.parser.parse('#' + ItemCode);  //解析checkbox
    }, function (data) {
    });
    params.qcEntityId = ParRef;
    params.ruleType = RuleType;
    ajax.set(params);
    ajax.start();
}

function Common_SetValue() {
    var itmValue = '';

    var val = arguments[1];
    var txt = arguments[2];

    if (typeof (arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#' + arguments[0]);
    if ($this.length < 1) return '';
    if (typeof val == 'undefined') val = '';
    if (typeof txt == 'undefined') txt = '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val(val);
    } else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val(val);
    } else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('setValue', val);
    } else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('setValue', val);
    } else if (className == 'hisui-combobox') {  //下拉框
        if (val != "" && txt == "") {
            itmValue = $this.combobox('setValue', val);
        } else {
            itmValue = $this.combobox('setValue', txt);
        }
    } else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('setValue', val);
    } else if (className == 'hisui-checkbox') {  // 单个复选框
        if (val == '') val = 0;
        itmValue = $this.checkbox('setValue', (val) ? true : false);
    } else if (className == 'hisui-radio') {  //单个单选框
        if (val == '') val = 0;
        itmValue = $this.radio('setValue', (val) ? true : false);
    } else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('setValue', val);
    }

    return itmValue;
}

function Common_GetValue() {
    var itmValue = '';

    if (typeof (arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#' + arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    } else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    } else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    } else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    } else if (className == 'hisui-combobox') {  //下拉框（多选下拉框没有封装）
        itmValue = $this.combobox('getValue');
    } else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    } else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.checkbox('getValue');
    } else if (className == 'hisui-radio') {  //单个单选框
        itmValue = $this.radio('getValue');
    } else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}

/**
 * 入组
 */
SdsMedicalGroup.inGroup = function (id) {
    /*var flag = false;
    if(id){
        flag = true;
    }else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        var index = Sys.open('入单病种管理',Sys.backendPath + '/sds/sdsmedicalgroup/in_group/' + id,['420px', '220px']);
        this.layerIndex = index;
    }*/
    //弹窗填写入组理由
    $('#divQCDic').show();
    $('#RuleDic').html("")
    Common_SetValue("RuleResume", "");
    $("#winQCDic").combobox({
        url: '/sds/sdsqcentity/noPageList',
        method: "get",
        valueField: 'id',
        textField: 'btDesc'
        , onSelect: function () {
            var DicID = Common_GetValue('winQCDic');
            Common_CheckboxToSDRule("RuleDic", DicID, 1, 1);
        }
    })
    SdsMedicalGroup.episodeId = id
    $('#winConfirmInfo').dialog({
        title: '单病种准入信息填写',
        width: 500,
        height: 300
    })
    $HUI.dialog('#winConfirmInfo').open();
};

function Common_CheckboxValue() {
    var ItemCode = arguments[0];
    var value = "";
    $("input[name='" + ItemCode + "']:checked").each(function () {
        value = value + $(this).val() + ",";
    });
    if (value != "") {
        value = value.substring(0, value.length - 1);
    }

    return value;
}

$('#SaveRule').on('click', function () {
    if (!SdsMedicalGroup.clicked) {
        SdsMedicalGroup.clicked = true;
        var RuleStr = Common_CheckboxValue('RuleDic');
        var Resume = $('#RuleResume').val()
        if ((RuleStr == "") && (Resume == "")) {
            $.messager.alert("错误提示", "入组原因和备注最少填写一项！", 'info');
            return;
        }
        var params = {};
        var ajax = new $ax(Sys.backendPath + "/sds/sdsopqcincase/inQcEntity", function (data) {
            if (parseInt(data) < 1) {
                $.messager.alert("错误提示", "入单病种失败!", 'info');
                return; //如果主记录保存失败  退出
            } else {
                $.messager.popover({msg: '操作成功！', type: 'success', timeout: 1000});
                SdsMedicalGroup.search2();
            }
            SdsMedicalGroup.clicked = false;
        }, function (data) {
            SdsMedicalGroup.clicked = false;
        });
        params.episodeId = SdsMedicalGroup.episodeId;
        params.qcDicId = Common_GetValue('winQCDic');
        params.ruleStr = RuleStr;
        params.resume = Resume;
        ajax.set(params);
        ajax.start();
        $HUI.dialog('#winConfirmInfo').close();
    }
})

/**
 * 查询病种入组病例列表
 */
SdsMedicalGroup.search2 = function () {
    //var dateType = $('#dateType1').datebox('getValue');//结束日期
    //出院日期
    var dateType = "2";
    var startDate = $('#startDate1').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate1').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    //var dept = $('#dept').datebox('getValue');
    var dept = $('#dept').combobox('getValue');
    var mrNum = $("#mrNum").val();
    var name = $("#name").val();
    var admDoctorName = $("#admDoctorName").val();
    var formStatus = $('#formStatus').combobox('getValue');
    var condition = $('#condition').combobox('getValue');

    SdsMedicalGroup.search(dateType, startDate, endDate, mrNum, name, admDoctorName, dept, formStatus, condition);
};

SdsMedicalGroup.clear = function () {
    $("#name").val('');
    $("#admDoctorName").val('');
    $("#mrNum").val('');
    $("#dept").combobox("setValue", "");
    $("#formStatus").combobox("setValue", "");
    $("#entityId").combobox("setValue", "");
    $("#isAuto").combobox("setValue", "");
}

SdsMedicalGroup.search = function (dateType, startDate, endDate, mrNum, name, admDoctorName, dept, formStatus, condition) {
    var queryData = {};
    queryData['dateType'] = dateType;
    queryData['startDate'] = startDate;
    queryData['endDate'] = endDate;
    queryData['mrNum'] = mrNum;
    queryData['name'] = name;
    queryData['admDoctorName'] = admDoctorName;
    queryData['admLocId'] = dept;
    queryData['formStatus'] = formStatus;
    queryData['condition'] = condition;
    if (formStatus != "2") {
        queryData['entityId'] = $("#entityId").combobox("getValue");
        queryData['isAuto'] = $("#isAuto").combobox("getValue");
    }
    SdsMedicalGroup.table.refresh({query: queryData, pageNumber: 1});
};

/**
 * 导出数据-不同条件
 */
SdsMedicalGroup.exportExcel = function (){

    var dateType = "2";
    var startDate = $('#startDate1').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate1').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    //var dept = $('#dept').datebox('getValue');
    var dept = $('#dept').combobox('getValue');
    var mrNum = $("#mrNum").val();
    var name = $("#name").val();
    var admDoctorName = $("#admDoctorName").val();
    var formStatus = $('#formStatus').combobox('getValue');

    var queryData = {};
    queryData['dateType'] = dateType;
    queryData['startDate'] = startDate;
    queryData['endDate'] = endDate;
    queryData['mrNum'] = mrNum;
    queryData['name'] = name;
    queryData['admDoctorName'] = admDoctorName;
    queryData['admLocId'] = dept;
    queryData['formStatus'] = formStatus;
    if (formStatus != "2") {
        queryData['entityId'] = $("#entityId").combobox("getValue");
        queryData['isAuto'] = $("#isAuto").combobox("getValue");
    }

    var longStart = Date.parse(startDate);
    var longEnd = Date.parse(endDate);
    if(longStart>longEnd){
        Sys.error("开始日期不可大于结束日期");
        return false;
    }

    Sys.loading("数据文件生成中,请耐心等待");
    var ajax = new $ax(Sys.backendPath + "/sds/sdsmedicalgroup/createExcel", function(data){
        Sys.closeLoading();
        if(data.message=="DHCC"){
            Sys.info("无数据可以导出，请更改查询条件。");
        }else{
            window.location.href = Sys.backendPath + "/sds/sdsmedicalgroup/excelDown/"+data.message;
            SdsMedicalGroup.table.refresh({query: queryData, pageNumber: 1});
        }
    },function(data){
        Sys.error("数据生成失败!" + data.responseJSON.message + "!");
    });
    ajax.set(queryData);
    ajax.setAsync(true);
    ajax.start();
}


$(function () {
    $('#winConfirmInfo').dialog({
        title: '',
        iconCls: "icon-w-edit",
        closed: true,
        modal: true,
        isTopZindex: true
    });

    // $("#formStatus").combobox({
    //     onSelect: function (rec) {
    //         if (rec.value == "2") {
    //             $("#entityId").parent().hide();
    //         } else {
    //             $("#entityId").parent().show();
    //         }
    //     }
    // });

    $("#entityId").parent().hide();
    $("#formStatus").combobox({
        onSelect: function (rec) {
            $("#entityId").combobox("setValue", "");
            if (rec.value == "2"||rec.value == "") {
                $("#entityId").parent().hide();
                $("#isAuto").parent().hide();
            } else if (rec.value == "1") {
                $("#entityId").parent().show();
                $("#isAuto").parent().hide();
            } else {
                $("#entityId").parent().show();
                $("#isAuto").parent().show();
            }
        }
    })
    $("#formStatus").combobox("select", 1);

    var dateType = "2";
    var startDate = $('#startDate1').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate1').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    var dept = $('#dept').datebox('getValue');

    var defaultColunms = SdsMedicalGroup.initColumn();
    var table = new BSTable(SdsMedicalGroup.id, Sys.backendPath + "/sds/sdsmedicalgroup/list", defaultColunms);
    table.setPaginationType("server");
    table.setPageSize(20);
    table.setShowRefresh(false);
    table.setShowColumns(false);
    table.setShowToggle(false);
    table.setShowExport(false);
    var b_height = document.documentElement.clientHeight;
    table.setHeight(b_height - 100);
    table.set("dateType", dateType);
    table.set("startDate", startDate);
    table.set("endDate", endDate);
    table.set("dept", dept);
    table.set('formStatus',$("#formStatus").combobox('getValue'));
    SdsMedicalGroup.table = table.init();
});

//在Jquery里格式化Date日期时间数据
function timeStamp2String(time) {
    var datetime = new Date();
    datetime.setTime(time);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    return year + "-" + month + "-" + date;
}
